package com.daffodil.easyfile.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.baidu.ueditor.ActionEnter;
import com.daffodil.core.exception.BaseException;
import com.daffodil.util.StringUtils;

/**
 * 百度编辑器附件文件上传接口
 * @author yweijian
 * @date 2021年2月7日
 * @version 1.0
 * @description
 */
@Controller
@RequestMapping("/easyfile")
public class UeditorController{

	@Value("${spring.servlet.upload.file-path}")
	private String rootPath;
	
	@Value("${spring.servlet.upload.ueditor.config-path:classpath:ueditor-config.json}")
	private String configPath;
	
	@RequestMapping("/ueditor")
	public void ueditor(HttpServletRequest request, HttpServletResponse response){
		PrintWriter writer = null;
		String action = request.getParameter("action");
		String returnType = request.getParameter("returnType");
		String callback = request.getParameter("callback");
		
		try {
			request.setCharacterEncoding("utf-8");
			response.setHeader("Content-Type", "text/html; charset=UTF-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setHeader("Access-Control-Allow-Methods","GET,POST,OPTIONS");
			
			if ("config".equals(action)) {
				response.setContentType("application/javascript");
			} else {
				response.setContentType("application/json");
			}
			if("postmsg".equals(returnType)) {
				response.setContentType("text/html");
			}
			
			if(!"config".equals(action) && StringUtils.isNotEmpty(callback)) {
				response.setContentType("text/javascript");
			}
			String result = new ActionEnter(request, configPath, rootPath).exec();
			writer = response.getWriter();
			writer.write(result);
			
		} catch (IOException e) {
			e.printStackTrace();
			throw new BaseException(e.getMessage());
		} finally {
			if(writer != null) {
				writer.flush();
				writer.close();
			}
		}
	}
}
